package com.example.yiparkapplication.activity.index.activity.ConvenientPaymentActivity;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.LongDef;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.codingending.popuplayout.PopupLayout;
import com.example.yiparkapplication.R;
import com.example.yiparkapplication.activity.PayActivity;
import com.example.yiparkapplication.activity.index.activity.myCoupons.MyCouponsActivity;
import com.example.yiparkapplication.constant.API;
import com.example.yiparkapplication.constant.Constant;
import com.example.yiparkapplication.entity.OrderBean;
import com.example.yiparkapplication.util.BaseActivity;
import com.example.yiparkapplication.util.Common;
import com.rey.material.widget.Button;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.bumptech.glide.Glide;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.BlockingDeque;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

//AppCompatActivity
public class CarOrderActivity extends BaseActivity implements View.OnClickListener, OnBannerListener {
    private String singleCarID;
    private String mFlag;
    private LinearLayout useCoupon;
    private Banner mBanner;
    private Handler handler = new Handler();
    private TextView mCouponInfo;
    private static String mUserId;
    private static String mPhone;
    private JSONObject mJoIn;
    private List<String> imageUrlList = new ArrayList<String>();
    private List<String> imageTitleList = new ArrayList<String>();
    private int urlSum = 0;
    private String viewUrlIn = null;
    private String viewUrlOut = null;
    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private String licensePlate;
    private String mPrice;
    private Button payButton;
    private String mRouteNameId = "";
    private String mCouponId = "";
    private OrderBean orderBean = new OrderBean();
    private String flag = "alipay";
    private boolean ifRestart = true;
    private boolean ifSetCoupon = false;

    public static void getUserId(String userID, String phone){
        mUserId = userID;
        mPhone = phone;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_order_details_layout);
        Intent intent = getIntent();
        singleCarID = intent.getStringExtra("singleCarID");
        mBanner = findViewById(R.id.banner);
        useCoupon = findViewById(R.id.id_use_coupon_action);
        useCoupon.setOnClickListener(this);
        mCouponInfo = findViewById(R.id.id_coupon_info);
        getSingleCarDetails(singleCarID);

        mFlag = intent.getStringExtra("flag");
        if ("false".equals(mFlag)){
            Toast.makeText(getApplicationContext(), "为保护用户隐私，部分功能不显示", Toast.LENGTH_LONG).show();
            useCoupon.setVisibility(View.GONE);
        }

        TextView abnormalVehicles = findViewById(R.id.id_declaration_abnormal_vehicles);
        abnormalVehicles.setOnClickListener(this);

        payButton = findViewById(R.id.id_pay);
        payButton.setOnClickListener(this);

        RadioGroup radioGroup = findViewById(R.id.id_pay_radio);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i){
                if (i == R.id.id_pay_ali){
                    flag = "alipay";
                }else{
                    flag = "wx";
                }
            }
        });
        ImageView downLoadIcon = findViewById(R.id.id_down_load_icon);
        downLoadIcon.setOnClickListener(this);
    }

    @Override
    public void onClick(View v){
        String viewUrl;
        Intent intent;
        switch(v.getId()){
            case R.id.id_down_load_icon:
                View downView = View.inflate(CarOrderActivity.this, R.layout.fragment_down_load_show_layout, null);
                PopupLayout popupLayout = PopupLayout.init(CarOrderActivity.this, downView);
                popupLayout.show(PopupLayout.POSITION_CENTER);
                TextView viewIn = downView.findViewById(R.id.id_download_view_in);
                viewIn.setOnClickListener(this);
                TextView viewOut = downView.findViewById(R.id.id_download_view_out);
                viewOut.setOnClickListener(this);
                break;
            case R.id.id_download_view_in:
                viewUrl = viewUrlIn;
                downloadAvi(viewUrl);
                break;
            case R.id.id_download_view_out:
                viewUrl = viewUrlOut;
                downloadAvi(viewUrl);
                break;
            case R.id.id_pay:
                if (mCouponId != null && !"".equals(mCouponId) && !"0".equals(mCouponId)){
                    orderBean.setCouponId(Integer.valueOf(mCouponId));
                }
                if (flag.equals("alipay")){
                    orderBean.setPayType("21");
                    getOrder();
                }else if(flag.equals("wx")){
                    Toast.makeText(getApplicationContext(), "暂不支持微信支付", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.id_use_coupon_action:
                if (!ifSetCoupon){
                    mCouponId = "";
                }
                intent = new Intent(CarOrderActivity.this, MyCouponsActivity.class);
                intent.putExtra("mRouteNameId", mRouteNameId);
                intent.putExtra("mCouponId", mCouponId);
                intent.putExtra("mPrice", mPrice);
                startActivityForResult(intent, Constant.GET_COUPON_CODE);
                break;
            case R.id.id_declaration_abnormal_vehicles:
                intent = new Intent(CarOrderActivity.this, ExceptionDeclareActivity.class);
                intent.putExtra("singleCarID", singleCarID);
                intent.putExtra("licensePlate", licensePlate);
                startActivity(intent);
                break;
        }
    }

    /**
     * 创建支付订单
     */
    private void getOrder(){
        orderBean.setNumber(0);
        OkHttpClient okHttpClient = new OkHttpClient();
        String json = JSONObject.toJSONString(orderBean);
        Log.d("orderbean", "getOrder: " + json);
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json;charset=utf-8"), json);
        Request request = new Request.Builder()
                .url(API.HOST + API.URL_CREATE_ORDER)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)throws IOException{
                String tempResponse = response.body().toString();
                JSONObject joOut = Common.tempResponseException(tempResponse, getApplicationContext());
                Log.d("创建订单", joOut.toString());
                int code = joOut.getIntValue("code");
                if (code == 100){
                    JSONObject joIn = joOut.getJSONObject("object");
                    String tradingRecordId = joIn.getString("tradingRecordId");
                    Double singleCarPrice = joIn.getDouble("singleCarPrice");
                    PayActivity.getPayInfo(tradingRecordId, mPrice, flag, 0, singleCarPrice);
                    Intent intent = new Intent(CarOrderActivity.this, PayActivity.class);
                    startActivity(intent);
                }else if (code == 31001){
                    new Thread(){
                        public void run(){
                            handler.post(runnablePayB);
                        }
                    }.start();
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), joOut.getString("msg"), Toast.LENGTH_LONG).show();
                    Looper.loop();
                }else{
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), joOut.getString("msg"), Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }
        });
    }

    private void downloadAvi(String viewUrl){
        try {
            if (viewUrl == null || "".equals(viewUrl)){
                Toast.makeText(getApplicationContext(), "暂无视频", Toast.LENGTH_LONG).show();
                return;
            }
            /**
             * 一个完整的，简单的，视频下载功能*/
            Toast.makeText(getApplicationContext(), "开始下载", Toast.LENGTH_LONG).show();
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(viewUrl));
            request.setDestinationInExternalPublicDir("", viewUrl.substring(viewUrl.lastIndexOf("/") + 1));
            DownloadManager downloadManager = (DownloadManager)getApplicationContext().getSystemService(Context.DOWNLOAD_SERVICE);
            downloadManager.enqueue(request);
        }catch(Exception e){
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "下载失败，没找到视频", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void OnBannerClick(int position){}

    private void getSingleCarDetails(String singleCarID){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(API.HOST + API.URL_GET_SINGLE_DETAIL + "?id=" + singleCarID + "&isCharge=" + 1 + "&userId=" + mUserId)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)throws IOException{
                String tempResponse = response.body().string();
                showSingleCarDetails(tempResponse);
            }
        });
    }

    private void showSingleCarDetails(String tempResponse){
        JSONObject joOut = Common.tempResponseException(tempResponse, getApplicationContext());
        int code = joOut.getIntValue("code");
        if (code == 100){
            JSONObject joIn = joOut.getJSONObject("object");
            mJoIn = joIn;
            int index = 0;
            index = setImage(joIn.getString("inPhotoAddress1_small"), index);
            index = setImage(joIn.getString("inPhotoAddress2_small"), index);
            index = setImage(joIn.getString("outPhotoAddress1_small"), index);
            index = setImage(joIn.getString("outPhotoAddress2_small"), index);

            if (!"false".equals(mFlag)){
                viewUrlIn = joIn.getString("inVideoAddress");
                viewUrlOut = joIn.getString("outVideoAddress");
            }

            new Thread(){
                public void run(){
                    handler.post(runnableText);
                }
            }.start();

            new Thread(){
                public void run(){
                    handler.post(runnableImg);
                }
            }.start();
        }else{
            Looper.prepare();
            Toast.makeText(getApplicationContext(), joOut.getString("msg"), Toast.LENGTH_LONG).show();
            Looper.loop();
        }
    }

    private int setImage(String url, int index){
        if (url != null && !"".equals(url)){
            index++;
            imageUrlList.add(url);
            imageTitleList.add("图片" + index);
        }
        if (url == null || "".equals(url)){
            urlSum++;
            if (urlSum == 4){
                new Thread(){
                    public void run(){
                        handler.post(runnableUrlSum);
                    }
                }.start();
            }
        }
        return index;
    }

    Runnable runnablePayB = new Runnable(){
        @Override
        public void run(){
            hiddenView();
        }
    };

    Runnable runnableUrlSum = new Runnable() {
        @Override
        public void run() {
            mBanner.setVisibility(View.GONE);
        }
    };

    Runnable runnableImg = new Runnable(){
      @Override
      public void run()  {
          mBanner = findViewById(R.id.banner);
          MyImageLoader mMyImageLoader = new MyImageLoader();
          mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE);
          mBanner.setImageLoader(mMyImageLoader);
          mBanner.setBannerAnimation(Transformer.Tablet);
          mBanner.setBannerTitles(imageTitleList);
          mBanner.setDelayTime(3000);
          mBanner.isAutoPlay(true);
          mBanner.setIndicatorGravity(BannerConfig.CENTER);
          mBanner.setImages(imageUrlList)
                  .setOnBannerListener(CarOrderActivity.this)
                  .start();
      }
    };

    private class MyImageLoader extends ImageLoader{
        @Override
        public void displayImage(Context context, Object path, ImageView imageView){
            Glide.with(context.getApplicationContext())
                    .load(path)
                    .into(imageView);
        }
    }

    Runnable runnableText = new Runnable(){
        @Override
        public void run(){
            TextView mSingleCarDetails = findViewById(R.id.id_single_car_details);
            TextView mSingleCarStartTime = findViewById(R.id.id_single_car_start_time);
            TextView mSingleCarEndTime = findViewById(R.id.id_single_car_end_time);
            TextView mStreetName = findViewById(R.id.id_street_name);
            TextView mSingleCarLicensePlate = findViewById(R.id.id_single_car_license_plate);
            TextView mSingleCarTruckSpace = findViewById(R.id.id_single_car_truck_space);
            TextView mSingleCarID = findViewById(R.id.id_single_car_ID);
            TextView mSingleCarPrice = findViewById(R.id.id_single_car_price);
            TextView mSingleCarPaidPrice = findViewById(R.id.id_single_car_paid_price);
            TextView mSingleCarTotalPrice = findViewById(R.id.id_single_car_total_price);
            TextView mParkingTime = findViewById(R.id.id_single_car_parking_time);

            String startTime = simpleDateFormat.format(mJoIn.getDate("singleCarStartTime"));
            String endTime = null;
            if (mJoIn.getDate("singleCarEndTime")==null){
                endTime = simpleDateFormat.format(new Date());
            }else{
                endTime = simpleDateFormat.format(mJoIn.getDate("singleCarEndTime"));
            }
            String carNumber = mJoIn.getString("singleCarLicensePlate");
            licensePlate = carNumber;
            Double singleCarPaid = mJoIn.getDouble("singleCarPaid");
            mSingleCarPaidPrice.setText(singleCarPaid.toString() + "元");
            Double singleCarPrice = mJoIn.getDouble("singleCarPrice");
            mSingleCarTotalPrice.setText(singleCarPrice.toString() + "元");
            if (singleCarPaid > 0 && singleCarPaid < singleCarPrice){
                mPrice = new BigDecimal(singleCarPrice - singleCarPaid).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
            }else{
                mPrice = new BigDecimal(singleCarPrice).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
            }
            int singleCarType = mJoIn.getIntValue("singleCarType");
            if (singleCarType != 1 && singleCarType != 0){
                //表明当前车单不是待付款车单
                payButton.setEnabled(false);
                payButton.setBackgroundColor(getResources().getColor(R.color.color_font_gray_ef));
                useCoupon.setVisibility(View.GONE);
            }

            mSingleCarDetails.setText(mJoIn.getString("streetDesc"));
            mSingleCarStartTime.setText(startTime);
            mSingleCarEndTime.setText(endTime);
            mStreetName.setText(mJoIn.getString("streetName"));
            mRouteNameId = mJoIn.getString("singleCarRouteName");
            mCouponId = mJoIn.getString("couponId");
            if (mCouponId != null && !"".equals(mCouponId) && !"0".equals(mCouponId)){
                useCoupon.setClickable(false);
            }
            mSingleCarID.setText(mJoIn.getString("singleCarId"));
            mSingleCarTruckSpace.setText(mJoIn.getString("singleCarTruckSpace"));
            if ("false".equals(mFlag)){
                //表明是通过便捷缴费进入的，需要隐藏部分信息
                String routeName = mJoIn.getString("streetName");
                //取得路段名称的第一个字，后面接着***就好了
                String routeNameInfo = routeName.charAt(0) + "***";
                mStreetName.setText(routeNameInfo);
                LinearLayout singleCarIDLayout = findViewById(R.id.id_single_car_ID_layout);
                singleCarIDLayout.setVisibility(View.GONE);
                LinearLayout singleCarTruckSpaceLayout = findViewById(R.id.id_single_car_truck_space_layout);
                singleCarTruckSpaceLayout.setVisibility(View.GONE);
            }
            mSingleCarLicensePlate.setText(carNumber);
            double price = Double.valueOf(mPrice);
            Long stayTime = mJoIn.getLong("stayTime");
            int hour = (int)(stayTime / 1000 / 3600);
            int minute = (int)(stayTime / 1000 % 3600 / 60);
            int seconds = (int)(stayTime / 1000 % 3600 % 60);
            StringBuilder finalTime = new StringBuilder();
            finalTime.append(hour);
            finalTime.append("小时");
            finalTime.append(minute);
            finalTime.append("分");
            finalTime.append(seconds);
            finalTime.append("秒");
            mParkingTime.setText(finalTime.toString());

            String couponName = mJoIn.getString("couponName");
            if (couponName != null && !"".equals(couponName)){
                mCouponInfo.setText(couponName);
                payButton.setText("继续付款");
            }else{
                //这个等下再写总的来说就是向后台查询优惠券信息
                getPlateVipList();
            }
            if ("桂林市".equals(Constant.LOCALE_CITY_NAME) && "10001".equals(mJoIn.getString("promotionId"))){
                payButton.setText("首单免费");
            }
            orderBean.setUserId(mUserId);
            orderBean.setCarNumber(carNumber);
            orderBean.setEndTime(mJoIn.getDate("singleCarEndTime").getTime());
            orderBean.setStartTime(mJoIn.getDate("singleCarStartTime").getTime());
            orderBean.setPrice(Double.valueOf(mPrice));
            orderBean.setPhone(mPhone);
            orderBean.setType("0");
            orderBean.setIdNumber(singleCarID);
            orderBean.setStreetId(mJoIn.getString("singleCarRouteName"));
        }
    };

    private int number = 0;
    private void getPlateVipList(){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request;
        if (mCouponId != null && !"".equals(mCouponId) && !"0".equals(mCouponId)){
            request = new Request.Builder()
                    .url(API.HOST + API.URL_GET_PLATEVIP_LIST + "?parkUserId=" + mUserId + "&streetId=" + mRouteNameId + "&couponId=" + mCouponId + "&price=" + mPrice)
                    .build();
        }else{
            request = new Request.Builder()
                    .url(API.HOST + API.URL_GET_PLATEVIP_LIST+ "?parkUserId=" + mUserId + "&streetId=" + mRouteNameId + "&price=" + mPrice )
                    .build();
        }
        okHttpClient.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)throws IOException{
                String tempResponse = response.body().string();
                JSONObject joOut = Common.tempResponseException(tempResponse,getApplicationContext());
                Log.d("获取用户优惠券", "onResponse: " + joOut.toString());
                int code = joOut.getIntValue("code");
                if (code == 100){
                    number = 0;
                    JSONArray object = joOut.getJSONArray("object");
                    if (object != null){
                        for (int i=0;i<object.size();i++){
                            JSONObject cardInfo = object.getJSONObject(i);
                            if (cardInfo.getIntValue("whether") == 0){
                                number++;
                            }
                        }
                        new Thread(){
                            public void run(){
                                handler.post(runnableCoupon);
                            }
                        }.start();
                    }
                }else{
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), joOut.getString("msg"), Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }
        });
    }

    Runnable runnableCoupon = new Runnable(){
        @Override
        public void run(){
            if (number > 0){
                mCouponInfo.setText(number + "张可用");
                mCouponInfo.setTextColor(getResources().getColor(R.color.color_red));
            }
        }
    };

    private void hiddenView(){
        payButton.setEnabled(false);
        payButton.setBackgroundColor(getResources().getColor(R.color.color_font_gray_ef));
        useCoupon.setVisibility(View.GONE);
    }

    @Override
    protected void onRestart(){
        super.onRestart();
        if (ifRestart){
            SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
            boolean paySuccess = pref.getBoolean("paySuccess", false);
            if (paySuccess){
                hiddenView();
                SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                editor.putBoolean("paySuccess", false);
                editor.apply();
            }
            if ("false".equals(mFlag)){
                finish();
            }
        }else{
            ifSetCoupon = true;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        switch(requestCode){
            case Constant.GET_COUPON_CODE:
                if (resultCode == Constant.POST_COUPON_CODE){
                    mCouponInfo.setText(data.getStringExtra("monthCardName"));
                    mCouponId = data.getStringExtra("couponId");
                    payButton.setText("继续付款");
                    int monthDiscountType = data.getIntExtra("monthDIscountType", 1);
                    double monthDiscountValue = data.getDoubleExtra("monthDiscountValue", 0.00);
                    double price = Double.valueOf(mPrice);
                    if (monthDiscountType == 0){
                        price = price * monthDiscountValue;
                    }else{
                        price = price - monthDiscountValue;
                        if (price < 0){
                            price = 0;
                        }
                    }
                    BigDecimal bigDecimal = new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_UP);
                    TextView mSingleCarPrice = findViewById(R.id.id_single_car_price);
                    orderBean.setCouponId(Integer.valueOf(mCouponId));
                    mPrice = bigDecimal.toString();
                    orderBean.setPrice(bigDecimal.doubleValue());
                    mSingleCarPrice.setText("￥" + bigDecimal);
                    ifRestart = false;
                }
                break;
        }
    }

}
